package com.umeox.stopwatch

import android.annotation.SuppressLint
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Bundle
import android.os.Vibrator
import android.util.Log
import android.view.WindowManager
import androidx.core.content.ContextCompat
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity
import com.umeox.stopwatch.databinding.TimeUpLayoutBinding

class TimeUpActivity : ThemeAppCompatActivity() {
    private lateinit var binding: TimeUpLayoutBinding
    private lateinit var player: MediaPlayer
    private var vibrator: Vibrator? = null
    private var audioManager: AudioManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = TimeUpLayoutBinding.inflate(layoutInflater)
        setContentView(binding.root)

        player = MediaPlayer.create(this, R.raw.alarm_default)
        vibrator = ContextCompat.getSystemService(this, Vibrator::class.java)
        audioManager = ContextCompat.getSystemService(this, AudioManager::class.java)

        binding.btnConfirm.setOnClickListener { finish() }
        binding.root.post {
            startAlarm()
        }
    }

    override fun onStop() {
        super.onStop()
        stopAlarm()
    }

    private fun keepWake() {
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    }

    private fun releaseWake() {
        window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    }

    private var ringFlag = false
    private fun startRing() {
        val ringerMode = audioManager?.ringerMode ?: 0
        if (ringerMode > 1) {
            ringFlag = true
            try {
                player.isLooping = true
                player.start()
            } catch (e: Exception) {
                Log.e("TimeUpActivity", "startRing", e)
            }
        }
    }

    private fun stopRing() {
        if (ringFlag) {
            player.stop()
            player.reset()
            player.release()
            ringFlag = false
        }
    }

    private var vibrateFlag = false
    private fun startVibrate() {
        val ringerMode = audioManager?.ringerMode ?: 0
        if (ringerMode > 0) {
            vibrateFlag = true
            @Suppress("DEPRECATION")
            vibrator?.vibrate(longArrayOf(600, 600, 600, 600), 0)
        }
    }

    private fun stopVibrate() {
        if (vibrateFlag) {
            vibrator?.cancel()
            vibrateFlag = false
        }
    }

    @SuppressLint("WakelockTimeout")
    private fun startAlarm() {
        keepWake()
        startRing()
        startVibrate()
    }

    private fun stopAlarm() {
        releaseWake()
        stopRing()
        stopVibrate()
    }
}
